using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Transactions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MeetingRoom.Domain;

namespace MeetingRoom.Service.Workflow.Implementation
{
    /// <summary>
    /// Summary description for SimpleWorkflow
    /// </summary>
    public class SimpleWorkflow : IWorkflow
    {
        protected string name;

        protected List<IWorkflowPhase> PreConditions;

        protected List<IWorkflowPhase> PostConditions;

        public SimpleWorkflow()
        {
            this.PreConditions = new List<IWorkflowPhase>();
            this.PostConditions = new List<IWorkflowPhase>();
        }

        public SimpleWorkflow(string name) : this()
        {
            this.name = name;
        }

        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        #region IWorkflow Members

        public void AddPreCondition(IWorkflowPhase interceptor)
        {
            this.PreConditions.Add(interceptor);
        }

        public void AddPostCondition(IWorkflowPhase postCondition)
        {
            this.PostConditions.Add(postCondition);
        }

        public void Execute(Schedule scheduleRequest)
        {
            try
            {
                foreach (IWorkflowPhase PreCondition in this.PreConditions)
                {
                    PreCondition.Execute(scheduleRequest);
                }
            }
            catch (Exception ex)
            {
                throw new WorkflowException("Workflow is aborted", ex);
            }

            using (TransactionScope scope = new TransactionScope())
            {
                foreach (IWorkflowPhase PostCondition in this.PostConditions)
                {
                    PostCondition.Execute(scheduleRequest);
                }
                scope.Complete();
            }
        }

        #endregion
    }
}